package com.kedacom.demo.sigar;
import java.io.File;
import java.io.IOException;

import org.hyperic.sigar.FileInfo;
import org.hyperic.sigar.FileWatcher;
import org.hyperic.sigar.FileWatcherThread;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;


public class FileWatcherDemo extends FileWatcher {
	public String confFilePath="F:\\config.ini";

	public FileWatcherDemo(Sigar sigar) {
		super(sigar);
		File configFile = new File(confFilePath);
		if(!configFile.exists()){
			this.onNotFound(null);
		}
		try {
			this.add(configFile);
		} catch (SigarException e) {
			e.printStackTrace();
		}
	}

	public void onChange(FileInfo info){
		System.out.println("onChange:"+info);
	}
	
	 public void onNotFound(FileInfo info) {
		 System.out.println("onNotFound:"+info);
		 File configFile = new File(confFilePath);
		 try {
			 System.out.println("try to create file:"+confFilePath);
			 configFile.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 }
	 
	 public void onException(FileInfo info, SigarException e) {
		 System.out.println("onException:"+info);
		 System.out.println("onException:"+e);
	 }
	
	 public void holdOn() {
			while (true) {// 驻留主线程
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// TODO 尚未处理异常
					e.printStackTrace();
				}
			}
		}
	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws SigarException 
	 */
	public static void main(String[] args) throws InterruptedException{
		// TODO Auto-generated method stub
		Sigar sigar = new Sigar();
		FileWatcherDemo fwd = new FileWatcherDemo(sigar);
		FileWatcherThread fwt = new FileWatcherThread();
		fwt.add(fwd);
		fwt.setInterval(1000);
		fwt.doStart();
		fwd.holdOn();
		//confFileWacher.setInterval(100);
		
	}

}
